import React, { Component } from 'react';
import { Message, Form, Input, Loading, Button, Tab } from '@alifd/next';
import { remote, IPC } from '../../../../utils/electron';
import { DB_SETTING } from '../../../../utils/db';

const FormItem = Form.Item;

export default class EditorGallery extends Component {
  static displayName = 'Setting';

  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      cosSetting: {},
      baseSetting: {},
    };
  }

  componentDidMount() {
    this.initBaseSetting();
    this.initCosSetting();
  }
  chooseOutDir = () => {
    const { baseSetting } = this.state;
    remote.dialog.showOpenDialog({
      properties: ['openDirectory'],
    }, (files) => {
      if (files) {
        baseSetting.saveDir = files[0]
        this.setState({
          baseSetting,
        });
      }
    });
  }
  initCosSetting = () => {
    DB_SETTING().where('key').equals('cos-js-v5-setting').first()
      .then((response) => {
        if (response) {
          let res = response.value || '';
          res = JSON.parse(res);
          this.setState({
            cosSetting: res,
          });
        }
      })
      .catch(() => {
        console.log('no=data');
      });
  }
  initBaseSetting = () => {
    DB_SETTING().where('key').equals('base-setting').first()
      .then((response) => {
        if (response) {
          let res = response.value || '';
          res = JSON.parse(res);
          localStorage.setItem('serveHost', res.serveHost);
          this.setState({
            baseSetting: res,
          });
        }
      })
      .catch(() => {
        console.log('no=base=setting=data');
      });
  }
  imgManager = () => {
    remote.dialog.showOpenDialog({
      properties: ['openFile', 'multiSelections'],
      filters: [
        { name: 'Images', extensions: ['jpg', 'png', 'gif'] },
      ],
    }, (files) => {
      files.forEach((path) => {
        // ipcRender.send('uploadImg', path, index);
        IPC('uploadImg', {
          path,
        });
      });
    });
  }
  handleSubmit = (data, validateErr) => {
    if (validateErr) {
      return false;
    }
    localStorage.setItem('outRootDir', data.title);
    localStorage.setItem('serveHost', data.serveHost);
    const { baseSetting } = this.state;
    if (baseSetting && Object.keys(baseSetting).length > 0) {
      DB_SETTING().where('key').equals('base-setting')
        .modify({
          key: 'base-setting',
          value: JSON.stringify(data),
        })
        .then(() => {
          Message.success('保存成功');
        });
    } else {
      DB_SETTING().add({
        key: 'base-setting',
        value: JSON.stringify(data),
      }).then(() => {
        Message.success('保存成功');
      }).catch((e) => {
        Message.error(e.toString());
      });
    }
    Message.success('保存成功');
  }
  saveCosData = (data, validateErr) => {
    if (validateErr) {
      return false;
    }
    const { cosSetting } = this.state;
    if (cosSetting && Object.keys(cosSetting).length > 0) {
      DB_SETTING().where('key').equals('cos-js-v5-setting')
        .modify({
          key: 'cos-js-v5-setting',
          value: JSON.stringify(data),
        })
        .then(() => {
          Message.success('保存成功');
        });
    } else {
      DB_SETTING().add({
        key: 'cos-js-v5-setting',
        value: JSON.stringify(data),
      }).then(() => {
        Message.success('保存成功');
      }).catch((e) => {
        Message.error(e.toString());
      });
    }
  }

  handleChange = (key, value) => {
    const { baseSetting } = this.state;
    baseSetting[key] = value;
    this.setState({
      baseSetting,
    });
  }

  render() {
    const { loading, cosSetting, baseSetting } = this.state;
    return (
      <div className="card-bg">
        <Tab>
          <Tab.Item title="基础设置" key="1">
            <Loading visible={loading} shape="fusion-reactor" style={{ display: 'block' }}>
              <Form style={{ width: '60%' }}>
                <FormItem label="文件保存目录:">
                  <Input name="saveDir" placeholder="输入描述" value={baseSetting.saveDir} disabled style={{ width: '60%' }} /> <Button type="primary" onClick={this.chooseOutDir.bind(this)}>选择</Button>
                </FormItem>
                <FormItem label="服务器地址:" required requiredMessage="请填写服务器地址">
                  <Input name="serveHost" value={baseSetting.serveHost} onChange={this.handleChange.bind(this, 'serveHost')} placeholder="请填写服务器地址" />
                </FormItem>
                <FormItem label="">
                  <Form.Submit validate onClick={this.handleSubmit}>保存</Form.Submit>
                </FormItem>
              </Form>
            </Loading>
          </Tab.Item>
          <Tab.Item title="腾讯云文件设置" key="2">
            <Loading visible={loading} shape="fusion-reactor" style={{ display: 'block' }}>
              <Form style={{ width: '60%' }}>
                <FormItem label="SecretId:" required requiredMessage="请填写SecretId">
                  <Input name="SecretId" defaultValue={cosSetting.SecretId} placeholder="请填写腾讯云SecretId" />
                </FormItem>
                <FormItem label="SecretKey:" required requiredMessage="请填写SecretKey">
                  <Input name="SecretKey" defaultValue={cosSetting.SecretKey} placeholder="请填写腾讯云SecretKey" />
                </FormItem>
                <FormItem label="存储桶Bucket:" required requiredMessage="请填写Bucket">
                  <Input name="Bucket" defaultValue={cosSetting.Bucket} placeholder="请填写腾讯云Bucket" />
                </FormItem>
                <FormItem label="区域Region:" required requiredMessage="请填写Region">
                  <Input name="Region" defaultValue={cosSetting.Region} placeholder="请填写腾讯云Region" />
                </FormItem>
                <FormItem label="">
                  <Form.Submit validate onClick={this.saveCosData}>保存</Form.Submit>
                </FormItem>
              </Form>
            </Loading>
          </Tab.Item>
        </Tab>
      </div>
    );
  }
}
